from flask import jsonify, request

from src.const.code import Code
from src.http.example import BlueprintHttpExample
from src.service.example.member_service import MemberService
from src.struct.dto.member_dto import MemberDTO
from src.struct.req.example.member_create_req import MemberCreateReq
from src.struct.req.example.member_update_req import MemberUpdateReq
from src.util.rs import Rs


@BlueprintHttpExample.route('/member-create', methods=['POST'])
def member_create():
    """创建用户"""
    # 验证请求参数
    member_create_req: MemberCreateReq = MemberCreateReq.Schema().load(request.get_json())
    #
    member = MemberService().create(member_create_req)
    #
    return jsonify(Rs(
        Code.OK,
        Code.message(Code.OK),
        {
            'member': MemberDTO.from_model(member),
        }
    ).to_dict())


@BlueprintHttpExample.route('/member-update', methods=['POST'])
def member_update():
    """编辑用户"""
    # 验证请求参数
    member_create_req: MemberUpdateReq = MemberUpdateReq.Schema().load(request.get_json())
    #
    member = MemberService().update(member_create_req)
    #
    return jsonify(Rs(
        Code.OK,
        Code.message(Code.OK),
        {
            'member': MemberDTO.from_model(member),
        }
    ).to_dict())


@BlueprintHttpExample.route('/member-delete/<int:member_id>')
def member_delete(member_id):
    """删除用户"""
    MemberService().delete(member_id)
    #
    return jsonify(Rs(
        Code.OK,
        Code.message(Code.OK)
    ).to_dict())


@BlueprintHttpExample.route('/member-all')
def member_all():
    return jsonify(Rs(
        Code.OK,
        Code.message(Code.OK),
        {
            'members': MemberService().all(),
        }
    ).to_dict())
